using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace SmartMedical.WinUI
{
    /// <summary>
    /// 病人挂号窗体
    /// 用于新增病人挂号信息，包括基础信息和病人详细信息
    /// </summary>
    public partial class PatientRegistrationForm : Form
    {
        #region 私有字段
        /// <summary>
        /// HTTP客户端，用于调用后端API
        /// </summary>
        private readonly HttpClient _httpClient;
        
        /// <summary>
        /// API基础URL - 写入API端口
        /// </summary>
        private const string API_BASE_URL = "http://localhost:5165";
        
        /// <summary>
        /// 当前选中的医生信息
        /// </summary>
        private DoctorInfo? _selectedDoctor;
        
        /// <summary>
        /// 当前选中的科室信息
        /// </summary>
        private DepartmentInfo? _selectedDepartment;
        #endregion
        
        #region 构造函数
        /// <summary>
        /// 初始化病人挂号窗体
        /// </summary>
        public PatientRegistrationForm()
        {
            InitializeComponent();
            
            // 初始化HTTP客户端
            _httpClient = new HttpClient();
            _httpClient.Timeout = TimeSpan.FromSeconds(30);
            
            // 初始化窗体
            InitializeForm();
        }
        #endregion
        
        #region 初始化方法
        /// <summary>
        /// 初始化窗体设置
        /// </summary>
        private void InitializeForm()
        {
            this.Text = "病人挂号";
            this.Size = new Size(1450, 900);
            this.StartPosition = FormStartPosition.CenterParent;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            
            // 初始化下拉框数据
            InitializeComboBoxes();
            
            // 设置默认值
            SetDefaultValues();
        }
        
        /// <summary>
        /// 初始化下拉框数据
        /// </summary>
        private void InitializeComboBoxes()
        {
            // 性别下拉框
            cmbGender.Items.Clear();
            cmbGender.Items.AddRange(new string[] { "男", "女" });
            cmbGender.SelectedIndex = 0;
            
            // 科室下拉框
            cmbDepartment.Items.Clear();
            cmbDepartment.Items.AddRange(new string[] { "内科", "外科", "妇科", "儿科", "急诊科", "心内科" });
            
            // 号类下拉框
            cmbRegistrationType.Items.Clear();
            cmbRegistrationType.Items.AddRange(new string[] { "普通号", "专家号", "急诊号" });
            cmbRegistrationType.SelectedIndex = 0;
            
            // 医师下拉框
            cmbDoctor.Items.Clear();
            cmbDoctor.Items.AddRange(new string[] { "李医生", "王医生", "赵医生", "陈医生", "刘医生" });
            
            // 婚姻状况下拉框
            cmbMaritalStatus.Items.Clear();
            cmbMaritalStatus.Items.AddRange(new string[] { "已婚", "未婚", "离异", "丧偶" });
            cmbMaritalStatus.SelectedIndex = 1;
        }
        
        /// <summary>
        /// 设置默认值
        /// </summary>
        private void SetDefaultValues()
        {
            // 设置默认日期
            dtpRegistrationDate.Value = DateTime.Now;
            dtpVisitDate.Value = DateTime.Now;
            dtpBirthDate.Value = DateTime.Now.AddYears(-30);
            
            // 生成默认挂单号
            txtRegistrationNo.Text = GenerateRegistrationNo();
            
            // 设置默认费用
            txtRegistrationFee.Text = "10.00";
            txtOtherFee.Text = "5.00";
        }
        
        /// <summary>
        /// 生成挂单号
        /// </summary>
        /// <returns>挂单号</returns>
        private string GenerateRegistrationNo()
        {
            return $"GH{DateTime.Now:yyyyMMddHHmmss}";
        }
        #endregion
        
        #region 事件处理方法
        /// <summary>
        /// 确定按钮点击事件
        /// </summary>
        private async void BtnConfirm_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证输入
                if (!ValidateInput())
                {
                    return;
                }
                
                // 创建挂号数据
                var registrationData = CreateRegistrationData();
                
                // 提交数据
                await SubmitRegistrationData(registrationData);
                
                MessageBox.Show("挂号成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"挂号失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
        
        /// <summary>
        /// 科室选择变化事件
        /// </summary>
        private void CmbDepartment_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 根据科室更新医师列表
            UpdateDoctorList();
        }
        
        /// <summary>
        /// 号类选择变化事件
        /// </summary>
        private void CmbRegistrationType_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 根据号类更新费用
            UpdateRegistrationFee();
        }
        
        /// <summary>
        /// 出生日期变化事件
        /// </summary>
        private void DtpBirthDate_ValueChanged(object sender, EventArgs e)
        {
            // 自动计算年龄
            var age = CalculateAge(dtpBirthDate.Value);
            txtAge.Text = age.ToString();
        }
        #endregion
        
        #region 业务逻辑方法
        /// <summary>
        /// 验证输入数据
        /// </summary>
        /// <returns>验证结果</returns>
        private bool ValidateInput()
        {
            // 验证必填字段
            if (string.IsNullOrWhiteSpace(txtPatientName.Text))
            {
                MessageBox.Show("请输入患者姓名", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtPatientName.Focus();
                return false;
            }
            
            if (string.IsNullOrWhiteSpace(txtCardNo.Text))
            {
                MessageBox.Show("请输入卡号", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtCardNo.Focus();
                return false;
            }
            
            if (cmbDepartment.SelectedIndex == -1)
            {
                MessageBox.Show("请选择科室", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cmbDepartment.Focus();
                return false;
            }
            
            if (cmbDoctor.SelectedIndex == -1)
            {
                MessageBox.Show("请选择医师", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cmbDoctor.Focus();
                return false;
            }
            
            // 验证费用格式
            if (!decimal.TryParse(txtRegistrationFee.Text, out _))
            {
                MessageBox.Show("挂单费格式不正确", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtRegistrationFee.Focus();
                return false;
            }
            
            if (!decimal.TryParse(txtOtherFee.Text, out _))
            {
                MessageBox.Show("其他费格式不正确", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtOtherFee.Focus();
                return false;
            }
            
            return true;
        }
        
        /// <summary>
        /// 创建挂号数据对象
        /// </summary>
        /// <returns>挂号数据</returns>
        /// <summary>
        /// 创建挂号数据对象
        /// </summary>
        /// <returns>挂号数据</returns>
        private RegistrationData CreateRegistrationData()
        {
            return new RegistrationData
            {
                PatientId = 0, // 新患者ID为0，后端会自动创建
                CardNo = txtCardNo.Text.Trim(),
                PatientName = txtPatientName.Text.Trim(),
                Gender = cmbGender.Text == "男" ? 1 : 0, // 转换为整数：0-女, 1-男
                BirthDate = dtpBirthDate.Value,
                Age = CalculateAge(dtpBirthDate.Value),
                Phone = txtPhone.Text.Trim(),
                Address = txtAddress.Text.Trim(),
                IdCard = txtIdCard.Text.Trim(),
                MaritalStatus = cmbMaritalStatus.Text,
                Ethnicity = txtNation.Text.Trim(),
                Education = txtCulture.Text.Trim(),
                Occupation = txtPosition.Text.Trim(),
                PostalCode = txtPostalCode.Text.Trim(),
                Department = cmbDepartment.Text,
                Doctor = cmbDoctor.Text,
                RegistrationType = cmbRegistrationType.Text,
                RegistrationFee = decimal.Parse(txtRegistrationFee.Text),
                OtherFee = decimal.Parse(txtOtherFee.Text),
                RegistrationDate = dtpRegistrationDate.Value,
                VisitDate = dtpVisitDate.Value,
                VisitTimeSlot = "上午", // 默认上午时段
                Status = "已挂号"
            };
        }
        
        /// <summary>
        /// 计算年龄
        /// </summary>
        /// <param name="birthDate">出生日期</param>
        /// <returns>年龄</returns>
        private int CalculateAge(DateTime birthDate)
        {
            var today = DateTime.Today;
            var age = today.Year - birthDate.Year;
            if (birthDate.Date > today.AddYears(-age))
                age--;
            return age;
        }
        
        /// <summary>
        /// 根据科室更新医师列表
        /// </summary>
        private void UpdateDoctorList()
        {
            cmbDoctor.Items.Clear();
            
            switch (cmbDepartment.Text)
            {
                case "内科":
                    cmbDoctor.Items.AddRange(new string[] { "李医生", "王医生" });
                    break;
                case "外科":
                    cmbDoctor.Items.AddRange(new string[] { "赵医生", "陈医生" });
                    break;
                case "妇科":
                    cmbDoctor.Items.AddRange(new string[] { "刘医生", "张医生" });
                    break;
                case "儿科":
                    cmbDoctor.Items.AddRange(new string[] { "孙医生", "周医生" });
                    break;
                case "急诊科":
                    cmbDoctor.Items.AddRange(new string[] { "吴医生", "郑医生" });
                    break;
                case "心内科":
                    cmbDoctor.Items.AddRange(new string[] { "马医生", "朱医生" });
                    break;
                default:
                    cmbDoctor.Items.AddRange(new string[] { "李医生", "王医生", "赵医生" });
                    break;
            }
            
            if (cmbDoctor.Items.Count > 0)
            {
                cmbDoctor.SelectedIndex = 0;
            }
        }
        
        /// <summary>
        /// 根据号类更新挂号费用
        /// </summary>
        private void UpdateRegistrationFee()
        {
            switch (cmbRegistrationType.Text)
            {
                case "普通号":
                    txtRegistrationFee.Text = "10.00";
                    break;
                case "专家号":
                    txtRegistrationFee.Text = "50.00";
                    break;
                case "急诊号":
                    txtRegistrationFee.Text = "20.00";
                    break;
                default:
                    txtRegistrationFee.Text = "10.00";
                    break;
            }
        }
        
        /// <summary>
        /// 提交挂号数据到后端API
        /// </summary>
        /// <param name="data">挂号数据</param>
        private async Task SubmitRegistrationData(RegistrationData data)
        {
            try
            {
                var json = JsonConvert.SerializeObject(data);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                
                var response = await _httpClient.PostAsync($"{API_BASE_URL}/api/Medical/CreateRegistration", content);
                
                if (!response.IsSuccessStatusCode)
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    throw new Exception($"API调用失败：{response.StatusCode} - {errorContent}");
                }
                
                // 解析响应获取挂号单号
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<dynamic>(responseContent);
                
                if (result?.Code == 200 && result?.Data != null)
                {
                    var registrationNo = result.Data.ToString();
                    txtRegistrationNo.Text = registrationNo;
                }
            }
            catch (HttpRequestException ex)
            {
                throw new Exception($"网络连接失败：{ex.Message}");
            }
            catch (Exception ex)
            {
                throw new Exception($"提交挂号数据失败：{ex.Message}");
            }
        }
        
        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            // 释放HTTP客户端资源
            _httpClient?.Dispose();
            base.OnFormClosed(e);
        }
        #endregion
    }
    
    #region 数据模型类
    /// <summary>
    /// 挂号数据模型
    /// </summary>
    public class RegistrationData
    {
        /// <summary>
        /// 患者ID
        /// </summary>
        public long PatientId { get; set; }
        
        /// <summary>
        /// 卡号
        /// </summary>
        public string CardNo { get; set; } = string.Empty;
        
        /// <summary>
        /// 患者姓名
        /// </summary>
        public string PatientName { get; set; } = string.Empty;
        
        /// <summary>
        /// 性别 (0-女, 1-男)
        /// </summary>
        public int Gender { get; set; }
        
        /// <summary>
        /// 出生日期
        /// </summary>
        public DateTime BirthDate { get; set; }
        
        /// <summary>
        /// 年龄
        /// </summary>
        public int Age { get; set; }
        
        /// <summary>
        /// 电话
        /// </summary>
        public string Phone { get; set; } = string.Empty;
        
        /// <summary>
        /// 地址
        /// </summary>
        public string Address { get; set; } = string.Empty;
        
        /// <summary>
        /// 身份证号
        /// </summary>
        public string IdCard { get; set; } = string.Empty;
        
        /// <summary>
        /// 婚姻状况
        /// </summary>
        public string MaritalStatus { get; set; } = string.Empty;
        
        /// <summary>
        /// 民族
        /// </summary>
        public string Ethnicity { get; set; } = string.Empty;
        
        /// <summary>
        /// 文化程度
        /// </summary>
        public string Education { get; set; } = string.Empty;
        
        /// <summary>
        /// 职业
        /// </summary>
        public string Occupation { get; set; } = string.Empty;
        
        /// <summary>
        /// 邮政编码
        /// </summary>
        public string PostalCode { get; set; } = string.Empty;
        
        /// <summary>
        /// 科室
        /// </summary>
        public string Department { get; set; } = string.Empty;
        
        /// <summary>
        /// 医师
        /// </summary>
        public string Doctor { get; set; } = string.Empty;
        
        /// <summary>
        /// 号类
        /// </summary>
        public string RegistrationType { get; set; } = string.Empty;
        
        /// <summary>
        /// 挂单费
        /// </summary>
        public decimal RegistrationFee { get; set; }
        
        /// <summary>
        /// 其他费
        /// </summary>
        public decimal OtherFee { get; set; }
        
        /// <summary>
        /// 挂号日期
        /// </summary>
        public DateTime RegistrationDate { get; set; }
        
        /// <summary>
        /// 就诊日期
        /// </summary>
        public DateTime VisitDate { get; set; }
        
        /// <summary>
        /// 就诊时段 (上午、下午、晚上)
        /// </summary>
        public string VisitTimeSlot { get; set; } = string.Empty;
        
        /// <summary>
        /// 状态
        /// </summary>
        public string Status { get; set; } = string.Empty;
    }
    
    /// <summary>
    /// 医生信息
    /// </summary>
    public class DoctorInfo
    {
        /// <summary>
        /// 医生ID
        /// </summary>
        public long Id { get; set; }
        
        /// <summary>
        /// 医生姓名
        /// </summary>
        public string Name { get; set; } = string.Empty;
        
        /// <summary>
        /// 科室
        /// </summary>
        public string Department { get; set; } = string.Empty;
        
        /// <summary>
        /// 职称
        /// </summary>
        public string Title { get; set; } = string.Empty;
    }
    
    /// <summary>
    /// 科室信息
    /// </summary>
    public class DepartmentInfo
    {
        /// <summary>
        /// 科室ID
        /// </summary>
        public long Id { get; set; }
        
        /// <summary>
        /// 科室名称
        /// </summary>
        public string Name { get; set; } = string.Empty;
        
        /// <summary>
        /// 科室描述
        /// </summary>
        public string Description { get; set; } = string.Empty;
    }
    #endregion
}